No. You only write the catch{}
blocks for the Exception
s you
wish to handle.
Other Exception
s are thrown to the caller of the method that caused the exception.
import java.util.* ; public class SquareUser { public static void main ( String[] a ) { Scanner scan = new Scanner( System.in ); int num = 0 ; boolean goodData = false; while ( !goodData ) { System.out.print("Enter an integer: "); try { num = scan.nextInt(); goodData = true; } catch (InputMismatchException ex ) { System.out.println("You entered bad data." ); System.out.println("Please try again.\n" ); String flush = scan.next(); } } System.out.println("The square of " + num + " is " + num*num ); } }
Exception
handling is important for user-friendly programs.
Above is the compute-the-square program again, this time written
so that the user is prompted again if the input is bad:
This is a common style for reading user input. It would be useful to play with this program.
Could
System.out.println("Enter an integer:");
be moved into the program's try{}
block?